/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package course.providers.jpa;

import course.entities.User;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author def
 */
@Stateless
public class UserProvider implements Serializable {

    private static final long serialVersionUID = 8851631564842454L;

    @PersistenceContext(unitName = "webPartPU")
    protected EntityManager em;

    public UserProvider() {
    }

    public User create() {
        User entity = new User();
        em.persist(entity);
        return entity;
    }

    public void update(User entity) {
        em.merge(entity);
    }

    public void delete(User entity) {
        em.remove(em.merge(entity));
    }

    public User findById(long id) {
        return (User) em.find(User.class, id);
    }

    public List<User> findAll() {
        Query q = em.createNamedQuery("User.findAll");
        return (List<User>) q.getResultList();
    }

    public boolean checkAvailability(String userName) {
        if (findByUserName(userName) == null) {
            return true;
        }
        return false;
    }

    public User findByUserName(String userName) {
        if (userName == null) {
            return null;
        }
        Query q = em.createQuery("SELECT u FROM User u WHERE u.userName = :userName").setParameter("userName", userName);
        List<User> resultList = q.getResultList();
        if (resultList.isEmpty()) {
            return null;
        }
        return resultList.get(0);
    }

}
